<template>
  <div class="loginContainer">
    <el-card>
      <div slot="header" class="clearfix">
        <span>登录</span>
      </div>
      <div class="text item">
        <el-form
          :model="formData"
          status-icon
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              type="text"
              v-model="formData.username"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="formData.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')"
              >提交</el-button
            >
            <el-button @click="resetForm('ruleForm')">重置</el-button>
            &nbsp;&nbsp;
             <el-link href="./Register" ><u><i>没有账号，请注册</i></u></el-link>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import {login} from '../api/users'
export default {
  data() {

    return {
      formData: {
         username:"",
        password: "",
        
      },
      rules: {
          // required 选择必填 trigger: 'blur' blur失去焦点
        username: [{required: true, message: '请输入用户名', trigger: "blur" }],
        password: [{ required: true,message: '请输入密码', trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          login(this.formData).then(({data})=>{
            if(data.code===1000){
              console.log(data);
              localStorage.setItem("token",data.data.token);
              localStorage.setItem("refreshToken",data.data.refreshToken);
              localStorage.setItem("name",data.data.username);
              localStorage.setItem("id",data.data.id);
              this.$router.push('/')
            }else{
               this.$message({type:'error',message:data.msg});
            }
          }).catch((err)=>{
            console.log(err);
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<style>
.loginContainer {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #eeeeee;
  height: 100vh;
}

.el-card.is-always-shadow {
  align-items: center;
  width: 40rem;
  height: 20rem;
}
.clearfix {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 35px;
}
.el-form-item__content{
   display: flex;
   justify-content: flex-end;
}
</style>